
using System;
using System.IO;
using System.Xml;
using DeploymentWang.Interfaces.Entities;
using DeploymentWang.Interfaces.Resources;

namespace DeploymentWang.Core.Writers
{
    /// <summary>
    /// 
    /// </summary>
    public class ConfigXmlFileWriter : ConfigXmlFileOperationBase
    {
        protected override ConfigViolations DoOperation(ConfigurationRequest request,
            ConfigSetting setting,
            string targetLocation,
            XmlDocument xmlDoc,
            XmlNode xmlNode)
        {
            if (!setting.IsActionDefined(DeploymentWangConstants.WellKnownActions.Set))
                return new ConfigViolations();
            if (string.CompareOrdinal(xmlNode.InnerText, setting.Value) == 0)
                return new ConfigViolations();

            var violations = new ConfigViolations();

            xmlNode.InnerText = setting.Value;

            try
            {
                if (request.Force)
                    File.SetAttributes(targetLocation, FileAttributes.Normal);

                xmlDoc.Save(targetLocation);
            }
            catch (UnauthorizedAccessException)
            {
                violations.Add(new ConfigViolation
                                   {
                                       Info = setting,
                                       Message = "Access denied, file is write protected"
                                   });
            }
            
            return violations;
        }
    }
}